package cn.easy.kitchen.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import cn.easy.base.service.BaseService;
import cn.easy.kitchen.bean.BomNutritionBean;
import cn.easy.kitchen.utils.ProjectUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.easy.base.bean.PageBean;
import cn.easy.kitchen.domain.MaterialOrder;
import cn.easy.kitchen.repository.MaterialOrderDao;

import javax.persistence.Query;

@Component
public class MaterialOrderService extends BaseService<MaterialOrder> {
    @Autowired
    private MaterialOrderDao	materialOrderDao;

    public Page<MaterialOrder> search(Map<String, Object> searchParams, PageBean pageBean) {
        return materialOrderDao.findAll(spec(searchParams), pageBean.toPageRequest(new Sort(Direction.DESC, "createdAt")));
    }

    public List<MaterialOrder> search(Map<String, Object> searchParams, Sort... sort) {
        return materialOrderDao.findAll(spec(searchParams), sort == null || sort.length == 0  ? new Sort(Direction.DESC, "createdAt") : sort[0]);
    }

    public List<BomNutritionBean> searchByParams(Map<String, Object> searchParams) {
        StringBuilder sql = new StringBuilder("SELECT base.name as material_name,type.name as nut_name, nut.content from ck_material_order mo ");
        sql.append("LEFT JOIN ck_material_base base on mo.material_base_id = base.id ");
        sql.append("LEFT JOIN ck_nutrition nut on nut.material_base_id = base.id ");
        sql.append("LEFT JOIN ck_nutrition_type type ON type.id = nut.nutrition_type_id ");
        sql.append("where mo.customer_id =:customerId ");
        sql.append("and mo.data_on =:dataOn ");
        sql.append("and type.NAME is not null ");

        Query query = entityManager.createNativeQuery(sql.toString());
        query.setParameter("customerId", searchParams.get("EQ_customerId"));
        query.setParameter("dataOn", ProjectUtil.formatDate(searchParams.get("GTE_dataOn")));

        List<Object[]> list = query.getResultList();
        Map<String, String> traceElementMap = ProjectUtil.getTraceElementMap();
        Map<String, BomNutritionBean> resultMap = new HashMap<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Object[] ob = list.get(i);
                String materialBaseName = ob[0].toString();
                //只取前五个
                if (resultMap.size() == 5 &&
                        resultMap.containsKey(materialBaseName)) {
                    break;
                }
                String nutName = ob[1].toString();
                BigDecimal nutValue = ProjectUtil.getBigDecimalVal(ob[2]);
                BomNutritionBean nutritionBean = resultMap.get(materialBaseName);
                if (nutritionBean == null) {
                    nutritionBean = new BomNutritionBean();
                    nutritionBean.setName(ProjectUtil.cutStrLength(materialBaseName, 5));
                    nutritionBean.setTraceElement(BigDecimal.ZERO);
                }
                switch (nutName) {
                    case "蛋白质":
                        nutritionBean.setProtein(nutValue);
                        break;
                    case "脂肪":
                        nutritionBean.setFat(nutValue);
                        break;
                    case "糖":
                        nutritionBean.setSugar(nutValue);
                        break;
                    case "膳食纤维":
                        nutritionBean.setDietaryFiber(nutValue);
                        break;
                }
                //若属于微量元素,则累加
                if (traceElementMap.get(nutName) != null) {
                    nutritionBean.setTraceElement(nutritionBean.getTraceElement().add(nutValue));
                }
                resultMap.put(materialBaseName, nutritionBean);
            }
        }
        return new ArrayList<>(resultMap.values());
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(String id) {
        materialOrderDao.delete(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteAll() {
        materialOrderDao.deleteAll();
    }

    public MaterialOrder getOne(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return materialOrderDao.findOne(id);
    }

    public List<MaterialOrder> findAll(List<String> idList) {
        return Lists.newArrayList(materialOrderDao.findAll(idList));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public MaterialOrder save(MaterialOrder materialOrder) {
        return materialOrderDao.save(materialOrder);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void save(List<MaterialOrder> materialOrderList) {
        materialOrderDao.save(materialOrderList);
    }

}


